﻿namespace FluentMvc.MvcIntegration
{
    using System;
    using System.Collections.Generic;
    using System.Web.Mvc;
    using Fasterflect;

    public class TemplateDataAnnotationsModelMetadataProvider : DataAnnotationsModelMetadataProvider
    {
        protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
        {
            var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
            if (containerType != null && containerType.IsClass && typeof(IModelInitializer<>).MakeGenericType(containerType).IsAssignableFrom(containerType))
            {
                var instance = typeof (TemplateEngine<>).MakeGenericType(containerType).CreateInstance();
                instance.CallMethod("SetMetadata", metadata, propertyName);
            }
            return metadata;
        }
    }
}